<?php
/**
 * Created by lzl
 * Date: 2021 2021/10/14
 * Time: 15:41
 */
namespace App\Services\Api;
use App\Exceptions\RequestException;
use App\Forms\BannerForms;
use App\Forms\UploadForm;
use App\Forms\UserForms;
use App\Models\Banner;
use App\Models\Good;
use App\Models\User;
use App\Models\UserShareCode;
use App\Services\BaseServices as Base;
use App\Utils\Upload;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Http\StreamResponse;


class ShareCodeServices extends Base
{

    /**
     * 批量生成所有分享海报并覆盖
     * @param User $user
     * @return bool
     * @throws RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public  function generate(User $user)
    {
        $backList = (new BannerForms())->getBannerList(['type' => Banner::SHARE_BACK]);

        if(filled($backList)){
            $url = [];

            foreach ($backList as $item){
               $url[] =  $this->generateImage($user, $item->url);
            }

            //保证整体性
            if(count($url)){
                $form = new UserForms();

                $form->deleteUserShareCode([
                    'uid' => $user->id,
                    'type' => UserShareCode::USER_SHARE,
                ]);
                foreach ($url as $item){
                    $form->createUserShareCode([
                        'uid'  => $user->id,
                        'type' => UserShareCode::USER_SHARE,
                        'url'  => $item
                    ]);
                }
            }

            return true;
        }

        return false;
    }


    /**
     * @param $path
     * @param $config
     * @return string
     * @throws RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function getQrCode($path, $config = [])
    {
        $app = Factory::miniProgram(config("wechat.mini_program.default"));

        $response = $app->app_code->get($path, $config);

        if ($response instanceof StreamResponse) {

            $qr_filename = $response->saveAs(storage_path('images'), uniqid('code') . '.png','png');

            return Upload::upload(storage_path('images/' . $qr_filename));
        }

        throw new RequestException($response['errmsg'] ?? '未知错误');
    }


    /**
     * @param User $user
     * @param $background
     * @return string
     * @throws RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function generateImage(User $user, $background)
    {
        $margin_left = 150;

        $margin_top = 330;

        $qrCode = $this->getQrCode('/pages/index/index?token=' . $user->openid, ['width' => 300]);

        $background_1 =  $this->createImageFromFile($background);

        $image_2 =  $this->createImageFromFile($qrCode);

        imagecopymerge($background_1, $image_2, $margin_left, $margin_top, 0, 0, imagesx($image_2), imagesy($image_2), 100);

        $path = storage_path('images/' . uniqid('code') . '.png');

        if (imagepng($background_1, $path)) {

            imagedestroy($background_1);
            return UploadForm::upload($path);
        }

    }


    /**
     * @param Good $goods
     * @param User $user
     * @param $market_price
     * @param $now_price
     * @return string
     * @throws RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function generateGoodsImage(Good $goods, User $user, $market_price, $now_price)
    {
        $im = imagecreatetruecolor(750, 1154);

        $fileName = storage_path('images/' . uniqid('code') . '.png');

        $qrCode = $this->getQrCode('/pages/goods/info?id='.$goods->id.'&token='.$user->openid, ['width' => '180']);

        //填充画布背景色
        $color = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $color);

        //字体文件
        $font_file = storage_path('font/msyh.ttf');
        $font_file_bold  = storage_path('font/msyhbd.ttf');

        //字体颜色
        $font_color_black = ImageColorAllocate ($im, 30, 30,40);
        $font_color_gray = ImageColorAllocate ($im, 153, 153, 153);
        $font_color_red = ImageColorAllocate ($im, 255, 45, 45);

        // 海报背景图
        list($g_w,$g_h) = getimagesize($goods->images);
        $goodImg = $this->createImageFromFile($goods->images);
        imagecopyresized($im, $goodImg, 0, 0, 0, 0, 750, 800, $g_w, $g_h);

        //二维码
        list($code_w,$code_h) = getimagesize($qrCode);
        $codeImg = $this->createImageFromFile($qrCode);
        imagecopyresized($im, $codeImg, 550, 820, 0, 0, 180, 180, $code_w, $code_h);

        //文字
        imagettftext($im, 30,0, 30, 870, $font_color_red, $font_file_bold, '￥'.$now_price);
        imagettftext($im, 18,0, 30, 940, $font_color_gray, $font_file, '原价：￥'.$market_price);

        if(mb_strlen($goods->goods_name) > 15){
            imagettftext($im, 24,0, 30, 1020, $font_color_black, $font_file_bold, mb_substr($goods->goods_name, 0, 15));
            imagettftext($im, 24,0, 30, 1070, $font_color_black, $font_file_bold, mb_substr($goods->goods_name, 15));
        }else{
            imagettftext($im, 24,0, 30, 1020, $font_color_black, $font_file_bold, $goods->goods_name);
        }

        imagettftext($im, 15,0, 560, 1020, $font_color_gray, $font_file_bold, '长按二维码识别');

        //输出图片
        imagepng($im, $fileName);

        //释放空间
        imagedestroy($im);
        imagedestroy($goodImg);
        imagedestroy($codeImg);

        return UploadForm::upload($fileName);
    }


    /**
     * 从图片文件创建Image资源
     * @param $file图片文件，支持url
     * @return bool|resource    成功返回图片image资源，失败返回false
     */
    function createImageFromFile($file){
        if(preg_match('/http(s)?:\/\//',$file)){
            $fileSuffix = $this->getNetworkImgType($file);
        }else{
            $file_info = getimagesize($file);
            $fileSuffix = $file_info[2];
        }

        if(!$fileSuffix) {
            return false;
        }

        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];

        $theImage = @imagecreatefromstring(file_get_contents($file,false, stream_context_create($stream_opts)));

//        switch ($fileSuffix){
//            case 'jpeg':
//                $theImage = imagecreatefromjpeg($file);
//                break;
//            case 'png':
//                $theImage = @imagecreatefrompng($file);
//                break;
//            case 'gif':
//                $theImage = @imagecreatefromgif($file);
//                break;
//            default:
//                break;
//        }

        return $theImage;
    }


    /**
     * 获取网络图片类型
     * @param $url网络图片url,支持不带后缀名url
     * @return bool
     */
    function getNetworkImgType($url){
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url); //设置需要获取的URL
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);//设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //支持https
        curl_exec($ch);//执行curl会话
        $http_code = curl_getinfo($ch);//获取curl连接资源句柄信息
        curl_close($ch);//关闭资源连接

        if ($http_code['http_code'] == 200) {
            $theImgType = explode('/',$http_code['content_type']);

            if($theImgType[0] == 'image'){
                return $theImgType[1];
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

}